<template>
  <t-modal
    :title="model.text"
    width="900px"
    :visible="visible"
    @ok="onSubmit()"
    @cancel="closeModal()"
    wrapClassName="add-modal-container"
    forceRender
    v-bind:confirmLoading="confirmLoading"
    v-bind="footer"
  >
    <div class="curve-modal-body">
      <a-form-model ref="ruleForm" :model="form" :rules="rules">
        <a-form-model-item label="上级公司" prop="pid">
          <depart-popup
            placeholder="请选择上级公司"
            url="/mdata/organization/getTreeSysOrganization"
            v-model="form.pid"
          ></depart-popup>
        </a-form-model-item>
        <a-form-model-item ref="proName" label="项目名称" prop="proName">
          <a-input
            v-model="form.proName"
            placeholder="请输入"
            :maxLength="255"
          />
        </a-form-model-item>
        <a-row :gutter="0">
          <a-col :span="12">
            <a-form-model-item label="排序" prop="sort">
              <a-input-number
                style="width: 100%"
                :min="0"
                :precision="0"
                placeholder="请输入"
                v-model="form.sort"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="工程类型" prop="engType">
              <a-select
                showSearch
                :filter-option="filterOption"
                v-model="form.engType"
                placeholder="请选择"
              >
                <a-select-option
                  :value="item.dicItemCode"
                  v-for="(item, index) in engTypeSource"
                  :key="index"
                >
                  {{ item.dicItemName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="0">
          <a-col :span="12">
            <!--投资金额 -->
            <a-form-model-item prop="roadMoney" label="投资金额(万元)">
              <a-input
                v-model="form.roadMoney"
                placeholder="请输入投资金额"
                :maxLength="14"
                @blur="roadMoneyBlur($event)"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <!-- 投资规模 -->
            <a-form-model-item label="投资规模">
              <a-input v-model="form.raodMoneyScale" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="0">
          <a-col :span="12">
            <a-form-model-item label="项目负责人" prop="contacts">
              <a-tree-select
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                treeNodeFilterProp="title"
                show-search
                allowClear
                :tree-data="treeData"
                placeholder="请选择"
                :replaceFields="{
                  children: 'children',
                  title: 'text',
                  key: 'uuid',
                  value: 'uuid',
                }"
                v-model="form.contactsCode"
                @change="changeContacts($event)"
              />
              <!-- <a-input v-model="form.contacts" placeholder="请输入项目负责人" /> -->
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="手机号" prop="contactsPhone">
              <a-input v-model="form.contactsPhone" placeholder="请输入" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="0">
          <a-col :span="24">
            <a-form-model-item label="省市县" prop="workArea">
              <a-cascader
                :options="provinceSource"
                :field-names="{
                  label: 'name',
                  value: 'name',
                  children: 'children',
                }"
                placeholder="请选择"
                v-model="form.workArea"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-form-model-item label="项目图片">
          <UploadImg
            :record="upLoadImgData"
            :config="upLoadImgConfigData"
            v-model="form.proImage"
            @change="
              (e) => {
                handleChange(e);
              }
            "
          />
        </a-form-model-item>
        <a-row :gutter="0">
          <a-col :span="12">
            <a-form-model-item label="创建人" prop="creator">
              <a-input v-model="form.creator" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="创建时间" prop="createTime">
              <a-input v-model="form.createTime" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
  </t-modal>
</template>

<script>
import { axios } from "@/utils/request";
import DepartPopup from "@/components/TopVUI/custom/DepartPopup";
import { mapGetters } from "vuex";
import UploadImg from "@/components/TopVUI/k-form-design/packages/UploadImg";
import { getNowDateStr } from "@/utils/util";
import { getDicItemByCode } from "@/api/common.js";
import areaData from "@/components/_utils/area-json.js";
import { addAttributeByKey, flatTreeData } from "@/utils/util.js";
export default {
  components: {
    UploadImg,
    DepartPopup,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    model: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      upLoadImgData: {
        //上传图片数据
        options: {
          uploadWay: "minio",
          width: "100%", //宽度
          drag: false, //是否可拖拽
          fileName: "file", //文件参数名
          multiple: false, //是否支持多选
          limit: 1, //上传最大数量
          disabled: false, //是否禁用
          data: "{}", //额外参数（json格式）
          listType: "picture-card", //上传列表的内建样式，支持三种基本样式 text, picture 和 picture-card
          action: "/document/minio/uploadfile", //上传请求地址
          headers: {}, //请求头部
          downloadWay: "a", //下载方式  可选a、ajax
          dynamicFun: "", //动态函数名
          placeholder: "上传", //上传区文字提示
          defaultValue: [], //默认值
        },
      },
      upLoadImgConfigData: {}, //上传图片数据
      confirmLoading: false,
      footer: {},
      form: {
        uuid: "",
        //上级公司
        pid: "",
        //项目编码
        proCode: "",
        //项目名称
        proName: "",
        //工程类型
        engType: undefined,
        //排序
        sort: "",
        //投资金额
        roadMoney: "",
        //投资规模
        raodMoneyScale: "",
        //项目负责人
        contactsCode: undefined,
        contacts: "",
        //手机号
        contactsPhone: "",
        //省市县
        workArea: [],
        //项目图片
        proImage: [],
        //创建人
        creator: "",
        //创建时间
        createTime: "",
      },
      rules: {
        pid: [{ required: true, message: "请选择上级公司", trigger: "change" }],
        proName: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
        ],
        sort: [{ required: true, message: "请输入排序" }],
        engType: [
          { required: true, message: "请选择工程类型", trigger: "change" },
        ],
        roadMoney: [
          { required: true, message: "请输入投资金额", trigger: "blur" },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,6})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: "请输入正确的投资金额，可保留六位小数",
          },
        ],
        contactsPhone: [
          { required: false },
          {
            pattern: /^1[0-9]{10}$/,
            message: "请输入正确的手机号",
          },
        ],
        workArea: [
          {
            required: true,
            message: "请选择省市县",
          },
        ],
      },
      //工程类型
      engTypeSource: [],
      //项目负责人
      treeData: [],
      //省市区
      provinceSource: areaData,
    };
  },
  computed: {
    ...mapGetters(["nickname", "userInfo"]),
  },
  watch: {
    visible: {
      handler(val) {
        this.$emit("update:visible", val);
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    //查询所有下拉框
    async getData() {
      //获取工程类型
      this.engTypeSource = await this.getDicCodeData("engineeringType");
      //项目管理负责人
      await this.getDirectorData();
      //
      if (this.model.text == "编辑") {
        this.getDetail();
      } else {
        this.form.creator = this.nickname;
        this.form.createTime = getNowDateStr(1);
      }
    },
    //查询字典表
    getDicCodeData(dicCode = "") {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: dicCode })
          .then((res) => {
            let { data } = res;
            resolve(data);
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },
    changeContacts(value, label, extra) {
      let flatData = flatTreeData(this.treeData, "children");
      if (!value) {
        this.form.contacts = "";
        this.form.contactsPhone = "";
        return;
      }
      this.form.contacts = flatData.find((v) => v.uuid == value).text;
      this.form.contactsPhone = flatData.find((v) => v.uuid == value).phone;
    },

    //项目负责人
    getDirectorData() {
      this.$post(`/mdata/organization/getTreeOrganizationAndUserData`)
        .then((res) => {
          this.treeData = res?.data ?? [];
          this.recursiveTree(this.treeData);
        })
        .catch((_) => {
          this.treeData = [];
        });
    },

    //处理角色树
    recursiveTree(data = []) {
      data.forEach((item) => {
        this.$set(item, "disabled", true);
        if (item.orgName) {
          item.text = item.orgName;
          item.uuid = item.id;
        }
        if (item.children && item.children.length > 0) {
          this.recursiveTree(item.children);
        }
        if (item.list && item.list.length > 0) {
          let array = [];
          item.list.forEach((v) => {
            array.push({
              text: v.userName,
              uuid: v.uuid,
              phone: v.userCellphone,
              disabled: false,
            });
          });
          item.children = item.children.concat(array);
        }
      });
    },

    //投资规模
    roadMoneyBlur() {
      let { roadMoney } = this.form;
      if (roadMoney < 5000 && roadMoney > 0) {
        this.form.raodMoneyScale = "5千万以下";
      } else if (roadMoney >= 5000 && roadMoney < 10000) {
        this.form.raodMoneyScale = "5千万-1亿";
      } else if (roadMoney >= 10000) {
        this.form.raodMoneyScale = "1亿以上";
      } else {
        this.form.raodMoneyScale = "";
      }
    },
    //项目图片
    handleChange(e) {
      this.form.proImage = e;
    },

    //详情
    getDetail() {
      let { sysProject } = this.model;
      this.form = {
        uuid: sysProject?.uuid,
        //排序
        sort: sysProject?.sort ?? "",
        //上级公司
        pid: sysProject?.pid ?? "",
        //项目编码
        proCode: sysProject?.proCode ?? "",
        //项目名称
        proName: sysProject?.proName ?? "",
        //工程类型
        engType: sysProject?.engType || undefined,
        //项目负责人
        contactsCode: sysProject?.contactsCode ?? undefined,
        contacts: sysProject?.contacts ?? undefined,
        //投资金额
        roadMoney: sysProject?.roadMoney || "",
        //投资规模
        raodMoneyScale: sysProject?.raodMoneyScale || "",
        //手机号
        contactsPhone: sysProject?.contactsPhone ?? "",
        //区域
        workArea: sysProject?.workArea ? sysProject?.workArea.split("@") : [],
        //项目图片
        proImage: JSON.parse(sysProject?.proImage ?? "[]"),
        //创建人
        creator: sysProject?.creator ?? "",
        //创建时间
        createTime: sysProject?.createTime ?? "",
      };
      //数据赋值 给img组件
      this.upLoadImgData.options.defaultValue = this.form?.proImage ?? [];
    },

    //提交
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let { form } = this;
          let formJson = {
            orgType: "org_type.04",
            //上级公司
            pid: form.pid,
            //项目编码
            proCode: form.proCode,
            //排序
            sort: form.sort,
            //项目名称
            proName: form.proName,
            //工程类型
            engType: form.engType,
            //投资金额
            roadMoney: form.roadMoney,
            //投资规模
            raodMoneyScale: form.raodMoneyScale,
            //项目负责人
            contactsCode: form?.contactsCode ?? "",
            contacts: form?.contacts ?? "",
            //省市县
            workArea: form?.workArea.join("@"),
            //手机号
            contactsPhone: form.contactsPhone,
            //项目图片
            proImage: JSON.stringify(form.proImage),
          };
          let url = "";
          //编辑
          if (form.uuid) {
            formJson.uuid = form.uuid;
            url = "/mdata/organization/updateProject";
          }
          //新增
          else {
            url = "/mdata/organization/saveProject";
          }
          this.confirmLoading = true;
          axios
            .post(url, formJson, {
              headers: {
                "Content-Type": "application/json",
              },
            })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("操作成功", 1.5);
                this.closeModal();
                this.$parent.getTableData();
              } else {
                this.$message.error(res?.message ?? "操作失败");
              }
            })
            .catch((_) => {
              this.$message.error(_?.message ?? "操作失败");
            })
            .finally((_) => {
              this.confirmLoading = false;
            });
        }
      });
    },

    //重置表单
    resetForm() {
      this.form = {
        uuid: "",
        //上级公司
        pid: "",
        //项目编码
        proCode: "",
        //项目名称
        proName: "",
        //工程类型
        engType: undefined,
        //排序
        sort: "",
        //项目负责人
        contactsCode: undefined,
        contacts: "",
        //投资金额
        roadMoney: "",
        //投资规模
        raodMoneyScale: "",
        //手机号
        contactsPhone: "",
        //省市县
        workArea: [],
        //项目图片
        proImage: [],
        //创建人
        creator: "",
        //创建时间
        createTime: "",
      };
      this.$refs.ruleForm.resetFields();
    },

    //关闭弹窗
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },

    selectContainer(triggerNode) {
      return triggerNode.parentNode;
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.add-modal-container {
  .ant-modal-body {
    padding: 0 !important;
  }
  .curve-modal-body {
    padding: 14px;
    box-sizing: border-box;
    max-height: 700px;
    overflow: hidden;
    overflow-y: auto;
    .ant-form-item {
      display: flex;
      .ant-form-item-label {
        flex-shrink: 0;
        width: 120px;
        white-space: pre-wrap;
        display: flex;
        justify-content: flex-end;
        line-height: 20px;
        margin-right: 2px;
        align-items: center;
      }
      .ant-form-item-control-wrapper {
        flex: 1;
        overflow: hidden;
      }
    }
  }
}
</style>
